package com.andova.capture;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;

public class ReturnButton extends View {
    private int size;

    private int center_X;
    private int center_Y;
    private float strokeWidth;

    private Paint paint;
    Path path;

    private final boolean isPortrait;
    private final DisplayMetrics metrics = new DisplayMetrics();

    public ReturnButton(Context context) {
        this(context, null);
    }

    public ReturnButton(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ReturnButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        isPortrait = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT; // 竖屏标志
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(metrics);
    }

    private void setMeasure(int size) {
        if (this.size > 0) return;
        this.size = size;
        center_X = size / 2;
        center_Y = size / 2;

        strokeWidth = size / 15f;

        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(Color.WHITE);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(strokeWidth);

        path = new Path();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        switch (MeasureSpec.getMode(isPortrait ? widthMeasureSpec : heightMeasureSpec)) {
            case MeasureSpec.EXACTLY:
                int mw = getMeasuredWidth();
                int mh = getMeasuredHeight();
                int threshold = (isPortrait ? metrics.widthPixels : metrics.heightPixels) / 2;
                setMeasure(isPortrait ? (Math.min(mw, threshold)) : (Math.min(mh, threshold)));
                break;
            case MeasureSpec.AT_MOST:
            case MeasureSpec.UNSPECIFIED:
            default:
                setMeasure((int) (isPortrait ? metrics.widthPixels / 12f : metrics.heightPixels / 12f));
        }
        setMeasuredDimension(size, size / 2);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        path.moveTo(strokeWidth, strokeWidth / 2);
        path.lineTo(center_X, center_Y - strokeWidth / 2);
        path.lineTo(size - strokeWidth, strokeWidth / 2);
        canvas.drawPath(path, paint);
    }
}
